# encoding=utf8

import os
import subprocess

import uiautomator2 as u2

from sdktest_module.multiTest.driver import Driver
from sdktest_module.utils import adbCommand


def check_null(origin_func):
    # @wrapper(origin_func) # 加上报错：UnboundLocalError: local variable 'wrapper' referenced before assignment
    def wrapper(self, *args, **kwargs):
        if not self.device_id:
            print("Warning: device_id is none， return!!!")
            return None
        return origin_func(self, *args, **kwargs)

    return wrapper


class AndroidDriver(Driver):
    def __init__(self, device, start_activity, role):
        super().__init__(device, role, '127.0.0.1', device.client_port)
        self.host_port = device.client_port
        self.start_activity = start_activity
        self.u2_device = None
        self.device_name = role
        # self.init_u2() # 设备信息mgr 传过来

    def init_u2(self):
        retry = 3
        while retry > 0:
            try:
                self.u2_device = u2.connect_usb(self.device_id)
                # 针对部分手机解锁两次
                # self.u2_device.unlock()
                # self.u2_device.unlock()
                self.device_name = self.role + '(' + self.u2_device.device_info['brand'] + '-' + \
                                   self.u2_device.device_info[
                                       'model'] + ')'
                print('\n')
                print('device_info:' + self.u2_device.device_info['brand'] + '-' + self.u2_device.device_info[
                    'model'] + '-'
                      + self.u2_device.device_info['serial'] + '-android' + self.u2_device.device_info['version'])
                # 正常退出
                return
            except:
                # 异常时打印当前设备
                retry = retry - 1
                print('当前在线adb设备:' + os.popen('adb devices').read())

    def initialize(self):
        """
        初始化 1：adb forward; 2.start watcher处理弹窗
        """
        self._adb_forward()
        # self.watcher()

    @check_null
    def _adb_forward(self):
        adbForwardCommand = "adb -s %s forward tcp:%d tcp:%d"
        # adbforward 映射
        forward = adbForwardCommand % (self.device_id, self.host_port, self.port)
        print("adb forward: " + forward)
        self.adbForwardSuprocess = subprocess.Popen(forward.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        output, unused_err = self.adbForwardSuprocess.communicate()
        self._print_log("{}, output:{}, err:{}".format(forward, output, unused_err))

    @check_null
    def watcher(self):
        device_brand = self.u2_device.device_info['brand'].lower()
        if device_brand == 'honor':
            self.u2_device.watcher.when("始终允许").click()
            self.u2_device.watcher.when("START NOW").click()
            self.u2_device.watcher.when("立即开始").click()
        elif device_brand == 'huawei':
            self.u2_device.watcher.when("允许").click()
            self.u2_device.watcher.when("始终允许").click()
            self.u2_device.watcher.when("START NOW").click()
            self.u2_device.watcher.when("立即开始").click()
        elif device_brand == 'samsung':
            self.u2_device.watcher.when("允许").click()
            self.u2_device.watcher.when("确认").click()
            self.u2_device.watcher.when("总是允许").click()
            self.u2_device.watcher.when("立即开始").click()
            self.u2_device.watcher.when("START NOW").click()
            self._print_log('samsung')
        elif device_brand == 'xiaomi':
            self.u2_device.watcher.when("立即开始").click()
            #TODO
            self._print_log('xiaomi')
        else:
            self.u2_device.watcher.when("立即开始").click()
            self.u2_device.watcher.when("允许").click()
        self.u2_device.watcher.start(1)
        self.u2_device.watcher.running()

    @check_null
    def stop_app(self):
        if not self.device_id:
            self._print_log('device is none')
            return
        adbCommand.forceStopApp(self.device_id)

    @check_null
    def start_app(self):
        # 清一下系统日志缓存，避免拿到上次跑用例的log
        adbCommand.clearDeviceLogCache(self.device_id)

        adbstartCommand = "adb -s %s shell am start -n %s"
        # adbstartCommand = "adb -s %s shell am start -n com.hummer.demo/com.hummer.demo.ui.MainActivity"
        self.startSP = subprocess.Popen((adbstartCommand % (self.device_id, self.start_activity)).split(),
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.STDOUT)
        output, unused_err = self.startSP.communicate()
        self._print_log("start app, output:{}, err:{}".format(output, unused_err))
        self.clear()  # 清理本地消息

    @check_null
    def install_app(self, url):
        self.u2_device.app_install(url)

    @check_null
    def finish(self):
        # 强制停止app
        # self.u2_device.watcher.stop()
        if not self.device_id:
            return

        # 先断开连接，避免stop app后， 一直重连
        self.tcpclient.disconnect()

        adbCommand.forceStopApp(self.device_id)
        self.adbForwardSuprocess.terminate()
